package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lzc
 * @Date 2022/7/13 13:57
 */
public class Flink03_Aggregate {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 2L, 20),
            new WaterSensor("sensor_2", 3L, 30),
            new WaterSensor("sensor_1", 4L, 40),
            new WaterSensor("sensor_2", 5L, 50),
            new WaterSensor("sensor_1", 6L, 60)
        );
        
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream);  // 把流转成一个动态表
        tEnv.createTemporaryView("sensor", table);
        
        
        // 1. table
        /*table
            .groupBy($("id"))
            .select($("id"), call(MyAvg.class, $("vc")).as("avg_vc"))
            .execute()
            .print();*/
        
        
        // 2. sql
        tEnv.createTemporaryFunction("my_avg", MyAvg.class);
        
        tEnv.sqlQuery("select id, my_avg(vc) from sensor group by id").execute().print();
        
        
    }
    
    public static class MyAvg extends AggregateFunction<Double, Avg> {
    
        // 返回最终的聚合结果
        @Override
        public Double getValue(Avg accumulator) {
            return accumulator.sum *1.0/ accumulator.count;
        }
    
        // 初始化累加器
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }
        
        // 返回值必须是void   方法名必须是accumulate
        // 第一个参数必须是累加器  , 剩下根据实际情况定
        public void accumulate(Avg acc, Integer vc){
            acc.sum += vc;
            acc.count++;
        }
    }
    
    public static class Avg {
        public Integer sum = 0;
        public Long count = 0L;
    }
    
}
